package com.bnz.user.controller;

import com.bnz.common.utils.PhoneFormatCheckUtils;
import com.bnz.pojo.R;
import com.bnz.user.entity.User;
import com.bnz.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author zfs
 * @since 2022-12-02
 */
@Controller    //返回为视图型
public class UserController {
    @Autowired
    private IUserService userService;
    @Value("${server.port}")
    private int port;

    //用户注册的首页
    @GetMapping({"/","/register.html"})
    public String register(HttpServletRequest request){
        //取得xxl-sso的登录用户名
        // XxlSsoUser user = (XxlSsoUser) request.getAttribute(Conf.SSO_USER);
        // System.out.println("name = " + user.getUsername());
        return "register";
    }

    //获取验证码
    @GetMapping("user/getCode")
    @ResponseBody
    public R getCode(String phone){
        //判断手机号是否存在
        if(PhoneFormatCheckUtils.isPhoneLegal(phone)){
            userService.sendCode(phone);
        }
        return R.ok();
    }

    //添加用户
    @PostMapping("user/add")
    @ResponseBody
    public R add(User user,String code){
        //验证输入的验证码与redis中保存的验证码是否是致
        if(userService.isValidCodeSuccess(user.getPhone(),code)){
            userService.add(user);
        }
        return R.ok();
    }

    //查询所有用户
    @GetMapping("/user/list")
    @ResponseBody
    public R list(){
        return R.ok().put("list",userService.list());
    }


    @GetMapping("/findAll")
    @ResponseBody
    public List<User> findAll(){
        System.out.println("port:" + port);
        return userService.list();
    }

    //根据用户id查询用户信息
    @GetMapping("/user/findById/{id}")
    @ResponseBody
    public R findById(@PathVariable Long id){
        User user = userService.findById(id);
        return R.ok().put("user",user);
    }

}
